<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="search_data.name" placeholder="请输入名字" style="width: 400px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="search_data.role" placeholder="请选择用户角色" clearable style="width: 160px" class="filter-item" filterable>
        <el-option v-for="item in roleList" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="onSeach">搜索</el-button>
      <!--<el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出</el-button>-->
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="onAddMoney">添加</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="filterData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="账号" prop="username" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" prop="nickname" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号" prop="phone" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createDate" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createDate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="所属部门" prop="areaName" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dep }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" prop="status" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1?'success':'danger'" class="el-status" @click="changeStatus(scope.row)">{{ scope.row.status | userStatus }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="280"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(scope.row,scope.$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <el-row>
      <el-col :span="24">
        <div class="pagination">
          <el-pagination
            v-if="paginations.total > 0"
            :page-size="paginations.page_size"
            :layout="paginations.layout"
            :total="paginations.total"
            :current-page.sync="paginations.page_index"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
    <!-- 弹框页面 修改用户信息-->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      center
    >

      <div class="form">
        <el-form
          ref="form"
          :model="form"
          :rules="form_rules"
          label-width="120px"
          style="margin:10px;width:auto;"
        >
          <el-form-item prop="username" label="姓名">
            <el-input v-model="form.username" type="username" />
          </el-form-item>
          <el-form-item prop="nickname" label="用户名：">
            <el-input v-model="form.nickname" type="nickname" />
          </el-form-item>

          <el-form-item prop="phone" label="手机号">
            <el-input v-model="form.phone" type="phone" />
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="form.areaId" filterable>
              <el-option
                v-for="item in depList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="enabled">
            <el-radio-group v-model="form.enabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>

          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitUser('form')">提 交</el-button>
      </span>

    </el-dialog>

  </div>
</template>

<script>
import { parseTime, getTime } from '@/utils'
import { getUserList, saveUser, delUser } from '@/api/user'
export default {
  filters: { // 局部过滤器
    userStatus: (s) => {
      return s === 1 ? '启用' : '禁用'
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('负责人手机号不可为空'))
      } else {
        if (value !== '') {
          const reg = /^1[3456789]\d{9}$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的手机号码'))
          }
        }
        callback()
      }
    }
    return {
      listLoading: false,
      tableKey: 0,
      paginations: {
        page_index: 1, // 当前位于哪页
        total: 0, // 总数
        page_size: 10, // 1页显示多少条
        layout: 'total,prev, pager, next '// 翻页属性
      },
      dialog: {
        show: false,
        title: '',
        option: 'edit'
      },
      filterData: [],
      search_data: {
        name: '',
        dep: ''
      },
      form: {},
      form_rules: {
        username: [
          { required: true, message: '账户名不能为空！', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '名称不能为空！', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '名称不能为空！', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      form_auth: {
        roleId: [
          { required: true, message: '用户角色不能为空！', trigger: 'blur' }
        ]
      },
      roleList: ['admin', 'user'],
      depList: [],
      dialogAuth: false,
      downloadLoading: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList() {
      let url = '?page=' + this.paginations.page_index + '&size=' + this.paginations.page_size
      if (this.search_data.name !== '') {
        url += '&name=' + this.search_data.name
      }
      if (this.search_data.role !== '') {
        url += '&role=' + this.search_data.role
      }
      this.filterData = [
        {
          'username': 'admin',
          'nickname': 'Jane',
          'phone': '18402554852',
          'createDate': '2018-02-02 12:30:00',
          'dep': '开发部',
          'role': 'admin',
          'status': 1,
          'enabled': 1
        },
        {
          'username': 'user',
          'nickname': 'Jay',
          'phone': '18402551140',
          'createDate': '2018-02-02 12:30:00',
          'dep': '测试部',
          'role': 'admin',
          'status': 1,
          'enabled': 1
        }
      ]
      this.paginations.total = this.filterData.length
      return
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getUserList(url).then(response => {
          this.listLoading = false
          this.filterData = response.data.content
          this.paginations.total = response.data.totalElements
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 添加用户 弹窗
    async onAddMoney() {
      this.dialog.title = '添加用户信息'
      this.dialog.option = 'add'
      if (this.depList.length === 0) {
        /* const res = await getDepList()
        this.depList = res.data*/
        this.depList = [
          {
            id: 1,
            name: '测试部门'
          },
          {
            id: 2,
            name: '测试部门2'
          }
        ]
      }
      this.initSavePage()
    },
    // 初始化弹窗数据源
    initSavePage(data) {
      this.dialog.show = true
      if (this.dialog.option === 'add') {
        this.form = {
          'username': '',
          'nickname': '',
          'phone': '',
          'dep': '',
          'role': '',
          'enabled': 1
        }
      } else {
        this.form = {
          'username': data.username,
          'nickname': data.nickname,
          'phone': data.phone,
          'dep': data.dep,
          'role': data.role,
          'enabled': data.enabled
        }
      }
    },
    // 编辑弹窗
    handleEdit(data) {
      this.dialog.title = '编辑信息'
      this.dialog.option = 'edit'
      if (this.depList.length === 0) {
        this.depList = [
          {
            id: 1,
            name: '开发部'
          },
          {
            id: 2,
            name: '测试部'
          },
          {
            id: 3,
            name: '商务部'
          }
        ]
      }
      this.initSavePage(data)
    },
    // 删除
    handleDel(data, index) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        return new Promise((resolve, reject) => {
          delUser(data.id).then(response => {
            if (response.message === 'success') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              // 前端删除
              this.filterData.splice(index, 1)
              this.paginations.total--
              if (this.paginations.page_index > Math.ceil(this.paginations.total / this.paginations.page_size)) {
                this.paginations.page_index = Math.ceil(this.paginations.total / this.paginations.page_size)
              }
              this.handleCurrentChange(this.paginations.page_index)
              resolve()
            } else {
              this.$message({
                type: 'success',
                message: '删除失败!'
              })
              resolve()
            }
          }).catch(error => {
            reject(error)
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索
    onSeach() { // 查找
      this.$message.info('完善中')
      this.paginations.page_index = 1
      this.getUserList()
    },
    // 翻页
    handleCurrentChange(page) {
      // 当前页
      if (page > Math.ceil(this.paginations.total / this.paginations.page_size)) {
        page = Math.ceil(this.paginations.total / this.paginations.page_size)
      }
      this.paginations.page_index = page
      this.getUserList()
    },
    // 提交数据
    onSubmitUser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.dialog.option === 'add') {
            this.$message.success('添加成功')
            this.form.createDate = getTime()
            this.filterData.push(this.form)
          } else {
            this.$message.success('编辑成功')
          }
          this.dialog.show = false
          /* let url = ''
          if (this.dialog.option === 'edit') {
            url = ''
          }
          // 表单数据验证完成之后，提交数据;
          return new Promise((resolve, reject) => {
            saveUser(url, this.from).then(response => {
              let messageHeard = '添加'
              if (this.dialog.option == 'edit') {
                messageHeard = '编辑'
              }
              if (response.message == 'success') {
                this.$message({
                  message: messageHeard + '成功！',
                  type: 'success'
                })
                resolve()
              } else {
                this.$message({
                  message: messageHeard + '失败！',
                  type: 'error'
                })
                this.dialog.show = false
                resolve(response)
              }
            }).catch(error => {
              reject(error)
            })
          })*/
        }
      })
    },
    // 改变状态
    changeStatus(data) {
      data.status = data.status === 1 ? 0 : 1
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}

</script>

<style scoped>
  .filter-container{
    margin-bottom: 20px;
  }
  .filter-item{
    margin-right: 10px;
  }
  .fillcontain {
    width: 100%;
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .pagination {
    text-align: right;
    margin-top: 10px;
  }
  .checkbox-style{
    padding-bottom: 20px;
    padding-left: 30px;
    padding-right: 30px;
    width: 100%;
  }
  .el-status:hover{
    cursor: pointer;
  }
</style>
